package com.tianqu.tms.www.car.controller;

import java.text.SimpleDateFormat;
import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsDaoException;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.DateUtil;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.core.webservice.weichat.api.MobileMessage;
import com.tianqu.tms.core.webservice.weichat.api.PullingExecutor;
import com.tianqu.tms.core.webservice.weichat.api.rpc.TransferDataSyn30900Bo;
import com.tianqu.tms.entity.Car;
import com.tianqu.tms.entity.Member;
import com.tianqu.tms.www.car.actionform.CarPendingLiftActionForm;
import com.tianqu.tms.www.car.viewhelper.CarPendingLiftViewHelper;


/**
 * @author mufeiyu
 * 库存移库 - 成功 controller
 */
public class CarStockTransferSuccessController extends TmsController{
	private Logger logger = Logger.getLogger(CarStockTransferSuccessController.class);
	public final static int FIXEDVALUE_5 = 5;
	public final static int FIXEDVALUE_6 = 6;
	public final static String LICENSEPLATE_NOEMPTY_STR_BEFORE = "【库存移库通知】您申请将您车行所登记的库存车辆（｛$车辆名称｝，｛$车牌号码｝）移库到｛$迁移到商户的商户短名｝，已经在｛$当前系统时间｝处理成功。";
	public final static String LICENSEPLATE_EMPTY_STR_BEFORE = "【库存移库通知】您申请将您车行所登记的库存车辆（｛$车辆名称｝，车架号（后6位）｛$VIN码｝）移库到｛$迁移到商户的商户短名｝，已经在｛$当前系统时间｝处理成功。";
	public final static String LICENSEPLATE_NOEMPTY_STR_AFTER = "【库存移库通知】｛$迁移前商户的商户短名｝申请将其车行所登记的库存车辆（｛$车辆名称｝，｛$车牌号码｝）移库到您车行库存内，已经在｛$当前系统时间｝处理成功。";
	public final static String LICENSEPLATE_EMPTY_STR_AFTER = "【库存移库通知】｛$迁移前商户的商户短名｝申请将其车行所登记的库存车辆（｛$车辆名称｝，车架号（后6位）｛$VIN码｝）移库到您车行库存内，已经在｛$当前系统时间｝处理成功。";	
	public final static String CAR_NAME = "车辆名称";
	public final static String CAR_NUMBER = "车牌号码";
	public final static String CAR_VIN = "VIN码";
	public final static String MEMBER_SHORT_NAME_BEFORE = "迁移到商户的商户短名";
	public final static String MEMBER_SHORT_NAME_AFTER = "迁移前商户的商户短名";
	public final static String SYSTEM_TIME = "当前系统时间";
	public final static String SIGN = "\\$";
	public final static String BEFOREBRACE = "｛";
	public final static String LATERBRACE = "｝";

	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = TxController.getTxController();

		// 添加事务提交异常捕获
		try {
			controller.begin();
			//CarPendingLiftActionForm form = (CarPendingLiftActionForm)uc.getInputForm();
			CarPendingLiftViewHelper viewhelper = (CarPendingLiftViewHelper)uc.getAttribute(TmsConstants.VIEWHELP);
			String pushContentB = "";
			String pushContentA = "";
			
			Car car = Car.getInstance();
			Member member = Member.getInstance();
			TmsUserProfile profile = uc.getUserProfile();

            member = member.findCarScoreByMemberId(String.valueOf(viewhelper.getToMemberId()));
			//更新库存车辆信息表需要的数据
			car.setSerial(viewhelper.getSerial());
			// #111
			car.setCompanyContactPerson(member.getContactOwner());
			car.setCompanyContactPhone(member.getContactPhone());
			car.setMemberId(viewhelper.getToMemberId());
			//更新库存车辆信息表
			car.updateMemberIdBySerial(car);
			
			
			//更新商户会员信息数据表
			if(viewhelper.getRegisterStatusNum() == 1)
			{
				member.updateUsedCarPort(viewhelper.getActiveMemberId(), viewhelper.getUsedCarPort(), - 1 ,"CarStockTransfer");
				member.updateUsedCarPort(viewhelper.getToMemberId(),member.getUsedCarPort(), + 1 ,"CarStockTransfer");
			}
			
			//插入库存车辆特殊处理记录表需要的数据
			car.setIsPush(viewhelper.getIsPush());
			car.setUpdateUserId(profile.getUniqueId());
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式 
			String updataTime = DateUtil.getCurrentTime();
			car.setUpdateTime(df.parse(updataTime));
			
			//插入库存车辆特殊处理记录表-迁移前商户会员推送信息保存处理		
			String pushContent = "";
			if(viewhelper.getIsPush() == 1)
			{			
				if(viewhelper.getLicensePlate() == null || viewhelper.getLicensePlate().length() <= 0)
				{
					pushContent = getPushContent(viewhelper.getCarName(),getVin(viewhelper.getVin()), member.getMemName(),updataTime,2);					
				} else {
					pushContent = getPushContent(viewhelper.getCarName(),viewhelper.getLicensePlate(), member.getMemName(),updataTime,1);
				}				
			}else if(viewhelper.getIsPush() == 2){			
				pushContent = "";
			}
			pushContentB = pushContent;
			car.setPushContent(pushContent);
			car.setHandleType(FIXEDVALUE_6);

			car.setAcceptorImage(viewhelper.getAcceptorImage());
			
			//插入库存车辆特殊处理记录表
			car.insertCarHandleInfo(car);
			
			//插入库存车辆特殊处理记录表-迁移到商户会员推送信息保存处理
			if(viewhelper.getIsPush() == 1)
			{
				if(viewhelper.getLicensePlate() == null || viewhelper.getLicensePlate().length() <= 0)
				{
					pushContent = getPushContent(viewhelper.getCarName(),getVin(viewhelper.getVin()),viewhelper.getMemName(),updataTime,4);
				} else {
					pushContent = getPushContent(viewhelper.getCarName(),viewhelper.getLicensePlate(),viewhelper.getMemName(),updataTime,3);
				}				
			}else if(viewhelper.getIsPush() == 2){			
				pushContent = "";
			}
			pushContentA = pushContent;
			car.setPushContent(pushContent);
			car.setHandleType(FIXEDVALUE_5);
			
			//插入库存车辆特殊处理记录表
			car.insertCarHandleInfo(car);
			
			controller.commit();
						
			// 10、【TMS_web】库存移库 =>【TMS_app】同步
			MobileMessage message = new MobileMessage();
			message.putValue("Serial", viewhelper.getSerial());
			message.setMessage("【TMS_web】库存移库 =>【TMS_app】同步,Serial为#Serial#");
			TransferDataSyn30900Bo api = new TransferDataSyn30900Bo();
			api.setMobileMessage(message);
			
			Car carInfo = Car.getInstance();
			carInfo = car.findMemberId(viewhelper.getSerial());
			
			api.setSerial(viewhelper.getSerial());
			api.setIsPush(car.getIsPush());
			if(carInfo != null)

			api.setRegisterStatus(viewhelper.getRegisterStatusNum());
			api.setMemberIdB(String.valueOf(viewhelper.getActiveMemberId()));
			api.setPushContentB(pushContentB);
			api.setMemberIdA(String.valueOf(viewhelper.getToMemberId()));
			api.setPushContentA(pushContentA);
			api.setMarketNo(TmsConstants.MARKET_NO);
			// #111 208
			api.setContactPerson(member.getContactOwner());
			api.setContactPhone(member.getContactPhone());
			
			PullingExecutor.getInstance().submit(api);

		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}

		logger.debug(this.getClass().getName() + "#execute was completed.");		
	}
	public String getPushContent(String carName,String carInfo,String memberName,String systemTime ,int type)
		throws TmsDaoException {
		String contentStr = "";
		//车牌号不为空的移库前信息
		if(type == 1)
		{
			contentStr = LICENSEPLATE_NOEMPTY_STR_BEFORE;
		} else if(type == 2){
			//车牌号为空的移库前信息
			contentStr = LICENSEPLATE_EMPTY_STR_BEFORE;
		} else if(type == 3){
			//车牌号不为空的移库到信息
			contentStr = LICENSEPLATE_NOEMPTY_STR_AFTER;
		} else if(type == 4){
			//车牌号为空的移库到信息
			contentStr = LICENSEPLATE_EMPTY_STR_AFTER;
		}
		contentStr = contentStr.replaceAll(SIGN, "").replaceAll(BEFOREBRACE, "").replaceAll(LATERBRACE, "");

        contentStr = contentStr.replaceAll(CAR_NAME, carName).replaceAll(CAR_NUMBER, carInfo)
        .replaceAll(CAR_VIN, carInfo).replaceAll(MEMBER_SHORT_NAME_BEFORE, memberName)
        .replaceAll(MEMBER_SHORT_NAME_AFTER, memberName).replaceAll(SYSTEM_TIME, systemTime); 
		return contentStr;
	}
	
	private  String getVin(String vin){
		String r = vin;
		if(StringUtil.isNotBlank(vin) && vin.length() > 6){
			r = vin.substring(vin.length() - 6);
		}
		return r;
	}
}
